﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VOL.Core.DBManager;
using VOL.Entity.DomainModels;
using VOL.MyTable.Repositories;

namespace VOL.MyTable.Services
{

    /// <summary>
    /// 泛微OA处理工具
    /// </summary>
    public class wfoa_tools
    {

        /// <summary>
        ///  根据登录用户，获取该用户的一级部门的负责人，可能会出现多个领导，需要手工选
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string[] get_oayi_mg_dfrom_userid(string userId)
        {
            string[] rntmg_name = { };
            Ren_oa ren = new Ren_oa();
            fk_depart depart = new fk_depart();
            Fk_reimService frser = new Fk_reimService();
            int? yjdepid = frser.get_oayidepidfrom_userid(userId);

            IQueryable<Ren_oa> sf_queryeable = Ren_oaRepository.Instance.FindAsIQueryable(t => (t.DEPARTMENTID == yjdepid && t.STATUS != 5));

            rntmg_name = sf_queryeable.Select(s => s.LOGINID).ToArray();//当前部门oaid对应的部门长



            return rntmg_name;
        }
        /// <summary>
        /// 根据用户帐号，获取该用户的一级部门ID,来自OA用户
        /// </summary>
        /// <returns></returns>
        public static int? get_oayidepidfrom_userid(string username)
        {
            // int rntdepid = 0;
            Ren_oa ren = new Ren_oa();
            fk_depart depart = new fk_depart();
            IQueryable<Ren_oa> sf_queryeable = Ren_oaRepository.Instance.FindAsIQueryable(t => (t.LOGINID == username));

            int? currdepartid = decimal.ToInt32(sf_queryeable.Select(s => s.DEPARTMENTID).FirstOrDefault());//当前部门oaid 也可能是科室

            int? yijdepid = currdepartid;
            while (yijdepid != 0)
            {
                IQueryable<fk_depart> depart_queryeable = fk_departRepository.Instance.FindAsIQueryable(t => (t.depid_oa == yijdepid));
                int? suppdepid = depart_queryeable.Select(t => t.supdepid_oa).FirstOrDefault();
                if (suppdepid == 0)
                {
                    break;//如果上级部门==0,说明本次循环就是一级部门，直接返回yijdepid
                }
                else
                {
                    yijdepid = suppdepid;
                }

            }

            return yijdepid;
        }
        /// <summary>
        /// 根据depidoa获取部门负责人
        /// </summary>
        /// <param name="depidoa"></param>
        /// <returns></returns>
        public static string get_bmfzr_from_depidoa(int yj_dep_oa_id)
        {

            string[] rntmg_name = { };
            Decimal?[] czid = { 5, 4 };//表示辞职状态
            //IQueryable<Ren_oa> sf_queryeable = Ren_oaRepository.Instance.FindAsIQueryable(t => t.DEPARTMENTID == yj_dep_oa_id && !czid.Contains(t.STATUS));//可能出现一个部门两个领导的情况
            string sql = "select * from oa_ren where DEPARTMENTID = "+ yj_dep_oa_id+ " and STATUS not in(5,4) and  managerid not in(select id from oa_ren where DEPARTMENTID =  " + yj_dep_oa_id + ")";//防止出现一个部门两个领导的情况
            List<Ren_oa> sf_queryeable= DBServerProvider.SqlDapper.QueryList<Ren_oa>(sql, "").ToList();
            rntmg_name = sf_queryeable.Select(s => s.LOGINID).ToArray();//当前部门oaid对应的部门长
            return string.Join(",",rntmg_name);
            
            /*string sqlstr = "select *from oa_depart where id=" + yj_dep_oa_id;
            List<dynamic> rnt_list = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();
            int bmfzr = int.Parse((string)(rnt_list[0].BMFZR));
            if (rnt_list.Count > 0)
            {
                List<Ren_oa> ls_ren_Oas = DBServerProvider.DbContext.Set<Ren_oa>().Where(w => w.ID == bmfzr).ToList();
                if (ls_ren_Oas.Count > 0)
                {
                    return ls_ren_Oas[0].LOGINID.ToString();
                }
                else
                    return "";
            }
            return "";*/

        }
        /// <summary>
        /// 根据登录人的ID获取分管领导username
        /// </summary>
        /// <param name="username">登录账户</param>
        /// <returns></returns>

        public static string get_ggld_from_userid(string username)
        {
            int? yj_dep_oa_id = get_oayidepidfrom_userid(username);
            if (yj_dep_oa_id == 301)//说明是一级部门是公司领导，直接找他的上一级领导
            {
                return get_manager_username(username);
            }
            string sqlstr = "select *from oa_depart where id=" + yj_dep_oa_id;
            List<dynamic> rnt_list = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();
            int bmfgld = int.Parse((string)(rnt_list[0].BMFGLD));//分管领导
            if (rnt_list.Count > 0)
            {
                List<Ren_oa> ls_ren_Oas = DBServerProvider.DbContext.Set<Ren_oa>().Where(w => w.ID == bmfgld).ToList();
                if (ls_ren_Oas.Count > 0)
                {
                    return ls_ren_Oas[0].LOGINID.ToString();
                }
                else
                    return "";
            }
            return "";

        }

        /// <summary>
        /// 根据用户账户返回用户真实名称
        /// </summary>
        /// <param name="loginid">用户账户(UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;)</param>
        /// <returns></returns>
        public static string get_realusername(string loginid)
        {
            string realusername = "";
            if (string.IsNullOrEmpty(loginid)) { return realusername; }
            Sys_User user = new Sys_User();
            DbSet<Sys_User> user_all=DBServerProvider.DbContext.Set<Sys_User>();
            realusername = user_all.Where(t => t.UserName == loginid).Select(t => t.UserTrueName).FirstOrDefault(); 
           return realusername;
        }
        /// <summary>
        /// 直接找username的上一级领导
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string get_manager_username(string username)
        {
            string m_username = "";

            // Ren_oa or = new Ren_oa();
            string sql = "select * from oa_ren where id in(select managerid from oa_ren t where STATUS=1 and loginid in(@username))";
            Ren_oa ro = DBServerProvider.SqlDapper.QueryFirst<Ren_oa>(sql, new { username });
            if (ro != null)
            {
                m_username = ro.LOGINID;
            }
            else
            {
                m_username = "";
            }


            return m_username;
        }


        /// <summary>
        /// 获取下一步骤编码
        /// </summary>
        /// <param name="reimid"></param>
        /// <param name="current_stepid"></param>
        /// <returns></returns>
        public static int? get_next_step(int reimid, int? current_stepid)
        {
            
            int? _nextstepid = Fk_reimfloatRepository.Instance.Find(t => t.reimid == reimid &&t.node_type=="key" &&t.stepid==current_stepid).Select(s => s.nextstepid).FirstOrDefault();
            if (_nextstepid == 9)  return _nextstepid;//下一步如果是9，直接返回9
            List<Fk_reimfloat> t_list= Fk_reimfloatRepository.Instance.Find(t=>t.stepid == _nextstepid &&t.reimid==reimid &&t.node_type=="key");
            //先获取下一步骤判断是否存在
            if (t_list.Count > 0)//说明存在下一步骤存在
            {
                while (1 == 1)
                {
                    string tsql = t_list[0].tjsql;
                    if (string.IsNullOrEmpty(tsql))
                    {
                        break;//说明没有SQL条件语句，跳出循环，直接return
                    }
                    else
                    {
                        tsql = tsql.Replace("@reim_id@", reimid.ToString()).Replace("@tj_je@", t_list[0].tj_je.ToString());
                        List<dynamic> rnt_list = DBServerProvider.SqlDapper.QueryList<dynamic>(tsql, "").ToList();
                        if (rnt_list.Count > 0)
                        {
                            break;//说明当前步骤要执行,满足条件跳出循环，直接return
                        }
                       return get_next_step(reimid, _nextstepid);////递归，只有当下一步骤不存在自动退出,这里一定要return 否则就无限死循环 2022年5月26日 11:01:00 
                    }
                    
                }
                return _nextstepid;
            }
            else
            {
                return 9;//归档，当下一步骤为空也认为归档
            }
            
        }
    }
}
